package link.jfire.socket.socketclient;

import java.io.IOException;
import java.nio.channels.AsynchronousChannelGroup;
import java.util.concurrent.ThreadFactory;

public class ChannelGroupSource
{
    private static AsynchronousChannelGroup channelGroup;
    static
    {
        try
        {
            channelGroup = AsynchronousChannelGroup.withFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {
                private int i = 1;
                
                public Thread newThread(Runnable r)
                {
                    return new Thread(r, "客户端通信处理线程-" + i++);
                }
            });
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    
    public static AsynchronousChannelGroup getChannelGroup()
    {
        return channelGroup;
    }
    
    public static void resetThreadNum(int size)
    {
        AsynchronousChannelGroup tmp = channelGroup;
        try
        {
            AsynchronousChannelGroup newChannelGroup = AsynchronousChannelGroup.withFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2, new ThreadFactory() {
                private int i = 1;
                
                public Thread newThread(Runnable r)
                {
                    return new Thread(r, "客户端通信处理线程-" + i++);
                }
            });
            channelGroup = newChannelGroup;
            tmp.shutdown();
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    
    public static void shutdown()
    {
        try
        {
            channelGroup.shutdownNow();
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }
}
